package controllers;

import java.util.List;

import models.Account;
import models.AccountItem;
import models.AccountType;
import models.FundsFlowDirection;
import models.IncomeAndOutcomeType;
import models.User;
import play.mvc.Controller;
import play.mvc.With;
import controllers.Secure.Security;

@With(Secure.class)
public class Accounts extends Controller {

	public static void edit(Long id) {
		if(id == null) {
			render();
		} else {
			Account account = null;
			account = Account.get(id);
			render(account);
		}
	}
	
	public static void save(Long id, String name, String description, AccountType type, Double balance) {
		String authorName = Security.connected();
		User owner = User.all().filter("loginName", authorName).get();
		
		Account account = null;
		if(id == null) {
			account = new Account(owner.id, name, description, type);
		} else {
			account = Account.get(id);
			account.name = name;
			account.description = description;
			account.type = type;
			account.balance = balance;
		}
		
		if(account.id == null) {
			account.insert();
		} else {
			account.update();
		}
		
		edit(account.id);
	}
	
	public static void list() {
		String authorName = Security.connected();
		User owner = User.all().filter("loginName", authorName).get();
		
		List<Account> accounts = Account.getUserAccounts(owner.id);
		render(accounts);
		
	}
	
	public static void items(Long accountId) {
		Account account = Account.get(accountId);
		
		List<AccountItem> items = account.getItems();
		
		render(account, items);		
	}
	
	public static void transfer(Long sourceId, Long targetId, Double amount) {
		Account source = Account.get(sourceId);
		Account target = Account.get(targetId);
		
		AccountItem sourceItem = new AccountItem(sourceId, "转出到[" + target.name + "]", FundsFlowDirection.out, amount);
		AccountItem targetItem = new AccountItem(targetId, "由[" + source.name + "]转入", FundsFlowDirection.in, amount);
		
		source.balance = source.balance - amount;
		target.balance = target.balance + amount;
		
		source.update();
		sourceItem.insert();
		target.update();
		targetItem.insert();
		
		render(source, target);
	}
	
	public static void editIncomeAndPaymentType(Long id) {		
		if(id == null) {
			render();
		} else {
			IncomeAndOutcomeType type = null;
			type = IncomeAndOutcomeType.get(id);
			render(type);
		}
	}
	
	public static void saveIncomeAndPaymentType(Long id, String name, FundsFlowDirection direction) {		
		IncomeAndOutcomeType type = null;
		if(id == null) {
			type = new IncomeAndOutcomeType(name, direction);
		} else {			
			type = IncomeAndOutcomeType.get(id);
			type.name = name;
			type.direction = direction;
		}
		
		if(type.id == null) {
			type.insert();
		} else {
			type.update();
		}
		
		editIncomeAndPaymentType(type.id);		
	}
	
	public static void income() {}
	public static void outcome() {}
}
